import smtplib
from email.mime.text import MIMEText
import os
from utils.logging_conf import logger

class MailSender:
    def __init__(self,email_address,email_password, smtp_server, smtp_port=587):
        self.EMAIL_ADDRESS = email_address
        self.EMAIL_PASSWORD = email_password
        self.SMTP_SERVER = smtp_server
        self.SMTP_PORT = smtp_port

    def send_email(self,to_email, subject, content,is_html=False):
        try:
            # 创建邮件内容
            type = "html" if is_html else "plain"
            msg = MIMEText(content, type, "utf-8")
            msg["From"] = self.EMAIL_ADDRESS
            msg["To"] = to_email
            msg["Subject"] = subject

            # 建立SMTP连接
            with smtplib.SMTP(self.SMTP_SERVER, self.SMTP_PORT) as server:
                logger.info("连接SMTP服务器成功")
                logger.info("TLS加密启动成功")
                server.ehlo()
                server.starttls()
                server.login(self.EMAIL_ADDRESS,self.EMAIL_PASSWORD)
                server.sendmail(self.EMAIL_ADDRESS, to_email, msg.as_string())
                logger.info(f"邮件已成功发送到 {to_email}")
        except smtplib.SMTPException as e:
            logger.error(f"{to_email}, SMTP错误:{e}")
        except Exception as e:
            logger.error(f"{to_email}, 其他错误:{e}")
            raise e